package com.dominator.shiro;

import com.dominFramework.core.typewrap.Dto;
import com.dominFramework.core.utils.JsonUtils;
import com.dominator.utils.api.ApiUtils;
import com.dominator.utils.dao.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authc.AnonymousFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author gsh
 */
@Slf4j
public class ApiFilter extends AnonymousFilter {

    private static RedisUtil ru = RedisUtil.getRu();


    @Override
    protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) {
        ApiUtils.checkFixTime(response);
        return authfilter(request);
    }


    public boolean authfilter(ServletRequest request) {
        HttpServletRequest req = (HttpServletRequest) request;
        try {
            req.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String reqUrl = req.getRequestURI();
        //是否忽略
        boolean res = ignoreUrl(reqUrl);
        Dto dto = JsonUtils.toDto(req.getParameter("paramStr"));
        if (dto==null){
            return true;
        }
        return true;
    }


    /**
     * 忽略url
     *
     * @param url
     * @return
     */
    private static  boolean ignoreUrl(String url) {
        // 验证规则
        String regEx = ".*(login|sms|weixin|uploadpics|yeel).*";
        // 编译正则表达式
        Pattern pattern = Pattern.compile(regEx);
        // 忽略大小写的写法
        Matcher matcher = pattern.matcher(url);

        System.out.printf(String.valueOf(matcher.matches()));
        //忽略首页的url
        boolean homepage = false;
        // 字符串是否与正则表达式相匹配
        if(matcher.matches() || homepage ){
            return  true;
        }
        return false;
    }

    public static void main(String[] args) {
        ru.setex("CheckMessage17621501628","123456",60*60*24*30);
    }

}
